<template>
  <el-dialog
    title="标签AI生成"
    v-model="visible"
    top="10vh"
    width="1000px"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="dataFormRef"
      :model="defaultForm"
      :rules="dataFormRules"
      label-position="right"
      label-width="120px"
      v-loading="loading"
    >
      <el-form-item label="产品名称" prop="content">
        <el-input v-model="defaultForm.content" placeholder="请输入产品名称，并用英文逗号隔开语种"></el-input>
        <el-alert title="如果需要生成耳机的标签，请输入耳机,中文，点击生成，AI会帮你生成相关的产品标签" type="info" :closable="false" />
        <el-button type="primary" @click="aiEvent">生成</el-button>
        
      </el-form-item>
      <el-form-item label="AI标签">
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
          >全选</el-checkbox
        >
        <el-checkbox-group
          v-model="checkedCities"
          @change="handleCheckedCitiesChange"
        >
          <el-checkbox v-for="item in aiArray" :key="item" :label="item">
            {{ item}}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="updateOrCreate">确定</el-button>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, type PropType } from 'vue'
import { UPDATE_MODEL_EVENT } from 'cm/contants'
import { createTags, createAiTags, type AiTags } from '@/api/tags'
import { ElMessage } from 'element-plus'
import appConfig from '@/config/index'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
    default: false
  }
})

const emit = defineEmits([UPDATE_MODEL_EVENT, 'change'])

const visible = ref<boolean>(false)

const defaultForm = ref<AiTags>({
  content: ''
})

const handleClose = () => {
  defaultForm.value = {
    content: ''
  }
  emit(UPDATE_MODEL_EVENT, false)
}

const dataFormRules = {
  content: [{ required: true, message: '请输入AI内容', trigger: 'blur' }]
}

const aiArray = ref<Array<string>>([])
const checkAll = ref(false)
const isIndeterminate = ref(false)
const checkedCities = ref<Array<string>>([])
const handleCheckAllChange = (val: Array<string>) => {
  checkedCities.value = val ? aiArray.value : [] as Array<string>
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === aiArray.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < aiArray.value.length
}

watch(() => props.modelValue,
  async () => {
    visible.value = props.modelValue;
  }
)

const loading = ref<boolean>(false);

const connectURL = ref(`${appConfig.api.websocketUrl}/aiTagsEvent`);
const websocket = ref<any>()
const aiEvent = async () => {
  aiArray.value = []
  loading.value = true

  if (defaultForm.value.content === '') {
    ElMessage({ type: 'error', message: `请您输入产品名称` })
    loading.value = false
    return false;
  }
  const value = defaultForm.value.content as string
  const textArray = value.split(',')
  const text = `帮我生成有关${textArray[0]}的标签 并只返回${textArray[1] ? textArray[1] : '中文'}，用英文逗号分割`
  const data = {
    event: 'aiTagsEvent',
    data: text
  }
  websocket.value = new WebSocket(connectURL.value);
  websocket.value.onopen = (e: object) => {
    sendWs(data);
  }
  websocket.value.onmessage = (e: any) => {
    let jsonData = JSON.parse(e.data);
    let array: Array<string> = []
    array = Array.from(new Set(jsonData.data.split(',')))
    aiArray.value = array;
    websocket.value.close()
  }
  websocket.value.onclose = (e: object) => {
    console.log('关闭websocket', e)
    loading.value = false
  }
  websocket.value.onerror = (e: object) => {
    console.log('websocket错误', e)
    loading.value = false
  }

  const sendWs = (data: object) => {
    websocket.value.send(JSON.stringify(data))
  }
}

const dataFormRef = ref()
const updateOrCreate = async () => {
  dataFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      const submitData = checkedCities.value.map(item => {
        return {
          title: item,
          orderNum: 0
        }
      })
      const res = await createAiTags(submitData)
      loading.value = false
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '生成成功' })
        emit('change')
        handleClose()
      } else {
        ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试！' })
      }
    }
  })
}
</script>

<style scoped>
</style>
